/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package our.gui;

import java.awt.AWTException;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.KeyboardFocusManager;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.UIManager;
import javax.swing.table.TableCellRenderer;

/**
 *
 * @author keysman
 */
public class ourTable extends JTable implements ourInterfaceCommonObj {
    // Definisco la classe che possiede le funzioni comuni a tutti gli oggetti a video
    public our.gui.commonObjectClass SETTINGS = new our.gui.commonObjectClass();
    public ourTable() {
        super();
//        our.gui.ourForm.LSTTABLES.add(this);
        addKeyListener(new java.awt.event.KeyAdapter() {
            @Override
            public void keyPressed(java.awt.event.KeyEvent evt) {
                KeyPressed(evt);
            }
            @Override
            public void keyTyped(java.awt.event.KeyEvent evt) {
                //tblBeniKeyTyped(evt);
            }
        });
    }

    /**
     * Questa funzione disabilita la gestione del mouse del campo ourTextField e in caso di MOUSE_CLICKED richiama
     * la funzione di gestione del parent: ourTextField
     * @param e
     */
    @Override
    protected void processMouseEvent(java.awt.event.MouseEvent e)
    {
        if(SETTINGS.getOurForm()!=null)
        {
            boolean bRet = true;
            if(e.paramString().indexOf("MOUSE_CLICKED")>=0)
            {
                bRet = SETTINGS.getOurForm().clickOnComponent(this);
                if(bRet) {
                    int iRow = rowAtPoint(e.getPoint());
                    setRowSelectionInterval(iRow, iRow);
                    if(e.getClickCount()==2)
                    {
                        try {
                            java.awt.Robot robot = new java.awt.Robot();
                            robot.keyPress(KeyEvent.VK_ENTER);
                            robot.keyRelease(KeyEvent.VK_ENTER);
                        } catch (AWTException ex) {
                            javax.swing.JOptionPane.showMessageDialog(null, ex.toString(),
                                                "ERROR",
                                                javax.swing.JOptionPane.ERROR_MESSAGE);
                        }
                    }
                    requestFocus();
                    return;
                }
            }
            if(!bRet) e.consume();
        } else if(e.paramString().indexOf("MOUSE_CLICKED")>=0) {
            if(getRowCount()>0)
            {
                java.awt.Point p = e.getPoint();
                int rowNumber = rowAtPoint( p );
                setRowSelectionInterval(rowNumber, rowNumber);
                requestFocus();
            }
            super.processMouseEvent(e);
        }
    }
 
    /**
     * Funzione invocata alla pressione di un tasto quando il fuoco è sulla tabella stessa
     * @param evt La struttura che descrive l'evento
     */
    private void KeyPressed(java.awt.event.KeyEvent evt) {
        // L'utente preme SHIFT+TAB
        if( (evt.getKeyCode() == java.awt.event.KeyEvent.VK_TAB ) &&
            (evt.isShiftDown()) )
        {
            evt.consume();
            KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
            kfm.focusPreviousComponent();
        }
        // L'utente preme TAB
        if( (evt.getKeyCode() == java.awt.event.KeyEvent.VK_TAB) &&
            (!evt.isShiftDown()) )
        {
            evt.consume();
            KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
            kfm.focusNextComponent();
        }
    
        // L'utente preme il pulsante 'Sù'
        if ( (evt.getKeyCode() == java.awt.event.KeyEvent.VK_UP) &&
            (evt.isActionKey()) &&
            (getSelectedRow() <= 0) )
        {
            // Sposto il fuoco all'elemento precedente alla griglia
            KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
            kfm.focusPreviousComponent();
        }
            
        // L'utente preme il pulsante 'Giù'
        if( (evt.getKeyCode() == java.awt.event.KeyEvent.VK_DOWN) &&
            (evt.isActionKey()) &&
            (getSelectedRow() == (getRowCount() - 1)) )
        {
            // Il l'elemento della griglia selezionato è l'utlimo e
            // l'utente preme il tasto 'giù', passo il fuoco all'elemento successivo
            KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
            kfm.focusNextComponent();
        }
    
        // L'utente preme il pulsante 'INVIO'
        
        // ** HO COMMENTATO QUESTA PARTE DI CODICE PERCHE' ALLA PRESSIONE DEL TASTO INVIO CORRISPONDE ANCHE
        // ** L'EVENTO INVIO CONTROLLATO DALLA MASCHERA
        if( (evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) && (getSelectedRow()==-1) )
        {
            KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
            kfm.focusNextComponent();
        }
    }

    /**
     * Paints empty rows too, after letting the UI delegate do
     * its painting.
     */
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        paintEmptyRows(g);

    }

    /**
     * Paints the backgrounds of the implied empty rows when the
     * table model is insufficient to fill all the visible area
     * available to us. We don't involve cell renderers, because
     * we have no data.
     */
    protected void paintEmptyRows(Graphics g) {
        java.awt.Dimension d = getPreferredScrollableViewportSize();
        final int rowCount = d.height / getRowHeight();
        final Rectangle clip = g.getClipBounds();
        for(int i=getRowCount(); i<rowCount; i++) {
            g.setColor(colorForRow(i));
            g.fillRect(clip.x, i * rowHeight, clip.width, i * rowHeight + rowHeight);
        }
    }

    /**
     * Changes the behavior of a table in a JScrollPane to be more like
     * the behavior of JList, which expands to fill the available space.
     * JTable normally restricts its size to just what's needed by its
     * model.
     */
    @Override
    public boolean getScrollableTracksViewportHeight() {
        if (getParent() instanceof JViewport) {
            JViewport parent = (JViewport) getParent();
            return (parent.getHeight() > getPreferredSize().height);
        }
        return false;
    }

    /**
     * Returns the appropriate background color for the given row.
     */
    protected Color colorForRow(int row) {
        return (row % 2 == 0) ? new Color(0xff, 0xff, 0xcb) : getBackground();
    }

    /**
     * Shades alternate rows in different colors.
     */
    @Override
    public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
        Component c = super.prepareRenderer(renderer, row, column);
        if (isCellSelected(row, column) == false) {
            c.setBackground(colorForRow(row));
            c.setForeground(UIManager.getColor("Table.foreground"));
        } else {
            c.setBackground(UIManager.getColor("Table.selectionBackground"));
            c.setForeground(UIManager.getColor("Table.selectionForeground"));
        }
        return c;
    }

    public boolean ISVALID(boolean bShowErrorMessage) {
        return true;
    }
}